/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.sys.controller;


import io.renren.common.annotation.SysLog;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.Assert;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.sys.dao.SysUserRoleDao;
import io.renren.modules.sys.entity.SysRoleEntity;
import io.renren.modules.sys.entity.SysUserAuthenticationEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.entity.SysUserVOEntity;
import io.renren.modules.sys.service.SysRoleService;
import io.renren.modules.sys.service.SysUserAuthenticationService;
import io.renren.modules.sys.service.SysUserRoleService;
import io.renren.modules.sys.service.FranchiseeService;
import io.renren.modules.sys.shiro.ShiroUtils;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/sys/franchisee")
public class FranchiseeController extends AbstractController {
	@Autowired
	private FranchiseeService franchiseeService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysUserRoleDao sysUserRoleDao;
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysUserAuthenticationService sysUserAuthenticationService;
	
	/**
	 * 所有用户列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sys:franchisee:list")
	public R list(@RequestParam Map<String, Object> params){
		PageUtils page = franchiseeService.queryPage(params);

		return R.ok().put("page", page);
	}
	
	/**
	 * 获取登录的用户信息
	 */
	@RequestMapping("/info")
	public R info(){
		return R.ok().put("user", getUser());
	}
	
	/**
	 * 修改登录用户密码
	 */
	@SysLog("修改密码")
	@RequestMapping("/password")
	public R password(String password, String newPassword){
		Assert.isBlank(newPassword, "新密码不为能空");

		//原密码
		password = ShiroUtils.sha256(password, getUser().getSalt());
		//新密码
		newPassword = ShiroUtils.sha256(newPassword, getUser().getSalt());
				
		//更新密码
		boolean flag = franchiseeService.updatePassword(getUserId(), password, newPassword);
		if(!flag){
			return R.error("原密码不正确");
		}
		
		return R.ok();
	}
	
	/**
	 * 用户信息
	 */
	@RequestMapping("/info/{userId}")
	@RequiresPermissions("sys:franchisee:info")
	public R info(@PathVariable("userId") Long userId){
		SysUserEntity users = franchiseeService.getById(userId);
		
		//获取用户所属的角色列表
		Long roleId = sysUserRoleService.queryRoleId(userId);
		users.setRoleId(roleId);

		SysUserAuthenticationEntity authenticationEntity = sysUserAuthenticationService.getById(users.getAuthenid());

		SysUserVOEntity user = new SysUserVOEntity();
		user.setUserEntity(users);
		user.setAuthenticationEntity(authenticationEntity);
		return R.ok().put("user", user);
	}
	
	/**
	 * 保存用户
	 */
	@SysLog("保存用户")
	@RequestMapping("/save")
	@RequiresPermissions("sys:franchisee:save")
	public R save(@RequestBody SysUserVOEntity uservo){
		SysUserEntity users = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
		SysRoleEntity roleEntity = null;
		Long roleId = sysUserRoleDao.queryRoleId(users.getUserId());
		SysRoleEntity role = sysRoleService.getById(roleId);
		if(role.getRoleName().indexOf("管理员")!=-1){//当前登陆用户为平台管理员，只能添加渠道
			roleEntity = sysRoleService.querySysRoleByRoleName("渠道");
			if(roleEntity==null){
				return R.error("没有渠道角色，请先添加该角色");
			}
		}
		if(role.getRoleName().indexOf("渠道")!=-1) {//当前登陆用户为渠道，没有权限
			return R.error("你没有权限执行该操作");
		}
		if(role.getRoleName().indexOf("店铺")!=-1){//当前登陆用户为店铺，没有权限添加任何用户
			return R.error("你没有权限执行该操作");

		}
		ValidatorUtils.validateEntity(uservo.getUserEntity(), AddGroup.class);

		//添加认证信息
		sysUserAuthenticationService.save(uservo.getAuthenticationEntity());

		uservo.getUserEntity().setAuthenid(uservo.getAuthenticationEntity().getId());
		//添加用户信息
		uservo.getUserEntity().setParentId(users.getUserId());//所属上级id
		franchiseeService.saveUser(uservo.getUserEntity());
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(uservo.getUserEntity().getUserId(), roleEntity.getRoleId());
		
		return R.ok();
	}
	
	/**
	 * 修改用户
	 */
	@SysLog("修改用户")
	@RequestMapping("/update")
	@RequiresPermissions("sys:franchisee:update")
	public R update(@RequestBody SysUserVOEntity uservo){
		ValidatorUtils.validateEntity(uservo.getUserEntity(), UpdateGroup.class);

		franchiseeService.update(uservo.getUserEntity());

		sysUserAuthenticationService.updateById(uservo.getAuthenticationEntity());
		
		return R.ok();
	}
	
	/**
	 * 删除用户
	 */
	@SysLog("删除用户")
	@RequestMapping("/delete/{userId}")
	@RequiresPermissions("sys:franchisee:delete")
	public R delete(@PathVariable("userId") Long userId){
		if(userId == 1){
			return R.error("系统管理员不能删除");
		}
		
		if(getUserId() == userId){
			return R.error("当前用户不能删除");
		}

		franchiseeService.removeById(userId);
		
		return R.ok();
	}
}
